﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace TooltracePC
{
    public class ServerNet
    {
        public static TextBox _tbMsg = null;
        public static ToolStripProgressBar _pbNet = null;

        public static int _port = 5000;
        public static int _index = 0;
        public static int _maxCout = 5;

        public Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
        public Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();

        Thread threadWatch = null; // 负责监听客户端连接请求的 线程；  
        Socket socketWatch = null;


        //
        public void Listen()
        {
            // 创建负责监听的套接字，注意其中的参数；  
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 创建包含ip和端口号的网络节点对象；  
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, _port);

            try
            {
                // 将负责监听的套接字绑定到唯一的ip和端口上；  
                socketWatch.Bind(endPoint);
            }
            catch (SocketException se)
            {
                showMsg("异常：" + se.Message);
                return;
            }

            // 设置监听队列的长度；  
            socketWatch.Listen(_maxCout);
            // 创建负责监听的线程；  
            threadWatch = new Thread(WatchConnecting);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            showMsg("服务器启动监听成功！");
        }


        /// <summary>  
        /// 监听客户端请求的方法；  
        /// </summary>  
        void WatchConnecting()
        {
            while (true)  // 持续不断的监听客户端的连接请求；  
            {
                // 开始监听客户端连接请求，Accept方法会阻断当前的线程；  
                Socket sokConnection = socketWatch.Accept(); // 一旦监听到一个客户端的请求，就返回一个与该客户端通信的 套接字；  
                showMsg("IP:" + sokConnection.RemoteEndPoint.ToString() + " 已连接");// 想列表控件中添加客户端的IP信息； 
                // 将与客户端连接的 套接字 对象添加到集合中；  
                dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection);
                _index++;
                 Thread thr = new Thread(RecMsg);
                thr.IsBackground = true;
                thr.Start(sokConnection);
                dictThread.Add(sokConnection.RemoteEndPoint.ToString(), thr);  //  将新建的线程 添加 到线程的集合中去。  
            }
        }


        void RecMsg(object sokConnectionparn)
        {
            Socket sokClient = sokConnectionparn as Socket;
            while (true)
            {
                // 定义一个1000byte的缓存区；  
                byte[] arrMsgRec = new byte[1024];
                // 将接受到的数据存入到输入  arrMsgRec中；  
                int length = -1;
                try
                {
                    length = sokClient.Receive(arrMsgRec); // 接收数据，并返回数据的长度；  
                }
                catch (SocketException se)
                {
                    //ShowMsg("异常：" + se.Message);
                    showMsg("异常：" + se.Message);
                    _index++;
                    // 从 通信套接字 集合中删除被中断连接的通信套接字；  
                    dict.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象；  
                    dictThread.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从列表中移除被中断的连接IP  
                    //lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString());
                    break;
                }
                catch (Exception e)
                {
                    showMsg("异常：" + e.Message);
                    _index++;
                    // 从 通信套接字 集合中删除被中断连接的通信套接字；  
                    dict.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象；  
                    dictThread.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从列表中移除被中断的连接IP  
                    //lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString());
                    break;
                }

                byte[] arrMsg = new byte[10];

                if (length > 0)
                {
                    //string strMsg = System.Text.Encoding.Default.GetString(arrMsgRec);
                    showMsg("收到数据,数据长度:" + length.ToString() + "\n");
                    byte[] cmd = new byte[4];
                    Array.Copy(arrMsgRec, 0, cmd, 0, 4);

                    

                    if (System.Text.Encoding.Default.GetString(cmd) == "SYNC")
                    {
                        showMsg("正在处理SYNC" + "\n");
                        byte[] id = new byte[10];
                        string str_id;
                        Array.Copy(arrMsgRec, 4, id, 0, 10);
                        str_id = System.Text.Encoding.Default.GetString(id).Replace("\0", "");

                        byte[] createMan = new byte[30];
                        string str_Man;
                        Array.Copy(arrMsgRec, 14, createMan, 0, 30);
                        str_Man = System.Text.Encoding.Default.GetString(createMan).Replace("\0", "");

                        byte[] createDate = new byte[20];
                        string str_Date;
                        Array.Copy(arrMsgRec, 44, createDate, 0, 20);
                        str_Date = System.Text.Encoding.Default.GetString(createDate).Replace("\0", "");

                        byte[] createTime = new byte[10];
                        string str_Time;
                        Array.Copy(arrMsgRec, 64, createTime, 0, 10);
                        str_Time = System.Text.Encoding.Default.GetString(createTime).Replace("\0", "");

                        byte[] fileName = new byte[40];
                        string str_FileName;
                        Array.Copy(arrMsgRec, 74, fileName, 0, 40);
                        str_FileName = System.Text.Encoding.Default.GetString(fileName).Replace("\0", "");

                        byte[] fileMd5 = new byte[32];
                        string str_FileMd5;
                        Array.Copy(arrMsgRec, 114, fileMd5, 0, 32);
                        str_FileMd5 = System.Text.Encoding.Default.GetString(fileMd5).Replace("\0", "");

                        byte[] fileStat = new byte[2];
                        string str_FileStat;
                        Array.Copy(arrMsgRec, 146, fileStat, 0, 1);
                        str_FileStat = System.Text.Encoding.Default.GetString(fileStat).Replace("\0", "");

                        DataTable dtResutl = null;
                        dbSync syncDB = new dbSync();

                        dtResutl = syncDB.getByFileName(str_FileName);
                        if (dtResutl.Rows.Count == 0)
                        {//add

                            arrMsg = System.Text.Encoding.Default.GetBytes("ADD");
                        }
                        else
                        {
                            if (dtResutl.Rows[0]["FILESTAMP"].ToString() == str_FileMd5)
                            {
                                arrMsg = System.Text.Encoding.Default.GetBytes("OK");
                            }
                            else
                            {//update
                                arrMsg = System.Text.Encoding.Default.GetBytes("ADD");
                            }
                            
                        }
                        sokClient.Send(arrMsg);
                    }
                    else //data
                    {
                        showMsg("正在处理数据文件\n");

                        byte[] tmpFN = new byte[32];
                        string strtmpFN;
                        Array.Copy(arrMsgRec, 4, tmpFN, 0, 32);
                        strtmpFN = System.Text.Encoding.Default.GetString(tmpFN).Replace("\0", "");
                        showMsg(strtmpFN + "\n");


                        byte[] lableid = new byte[50];
                        string strlableid;
                        Array.Copy(arrMsgRec, 36, lableid, 0, 50);
                        strlableid = System.Text.Encoding.Default.GetString(lableid).Replace("\0", "");
                        showMsg(strlableid + "\n");

                        byte[] lablename = new byte[50];
                        string strlablename;
                        Array.Copy(arrMsgRec, 86, lablename, 0, 50);
                        strlablename = System.Text.Encoding.Default.GetString(lablename).Replace("\0", "");
                        showMsg(strlablename + "\n");

                        byte[] lableno = new byte[30];
                        string strlableno;
                        Array.Copy(arrMsgRec, 136, lableno, 0, 30);
                        strlableno = System.Text.Encoding.Default.GetString(lableno).Replace("\0", "");
                        showMsg(strlableno + "\n");

                        arrMsg = System.Text.Encoding.Default.GetBytes("OK");
                        sokClient.Send(arrMsg);
                    }

                }
                




                /*if (arrMsgRec[0] == 0)  // 表示接收到的是数据；  
                {
                    string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1);// 将接受到的字节数据转化成字符串；  
                    ShowMsg(strMsg);
                }*/
                /*if (arrMsgRec[0] == 1) // 表示接收到的是文件；  
                {
                    SaveFileDialog sfd = new SaveFileDialog();

                    if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {// 在上边的 sfd.ShowDialog（） 的括号里边一定要加上 this 否则就不会弹出 另存为 的对话框，而弹出的是本类的其他窗口，，这个一定要注意！！！【解释：加了this的sfd.ShowDialog(this)，“另存为”窗口的指针才能被SaveFileDialog的对象调用，若不加thisSaveFileDialog 的对象调用的是本类的其他窗口了，当然不弹出“另存为”窗口。】  

                        string fileSavePath = sfd.FileName;// 获得文件保存的路径；  
                                                           // 创建文件流，然后根据路径创建文件；  
                        using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
                        {
                            fs.Write(arrMsgRec, 1, length - 1);
                            ShowMsg("文件保存成功：" + fileSavePath);
                        }
                    }
                }*/
            }
        }


        public void init(TextBox tb, ToolStripProgressBar pb)
        {
            _tbMsg = tb;
            _pbNet = pb;
        }



        //
        public void showMsg(string str)
        {
            if (_tbMsg == null) { return; }
            if (string.IsNullOrEmpty(str)) { return; }
            _tbMsg.Text = _tbMsg.Text + str + "\r\n";

        }


        //获取本地的IP地址
        public string getLocalIP()
        {
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }







    }   
}
